<?php

/**
 * Memory Cache
 * @author ReGeDa
 */
class Memcacher extends Plugin_Object {

	/**
	 * Cacher object
	 * @var Memcache
	 */
	private $cacher;

	/**
	 * Constructor
	 */
	public function __construct() {
		parent::__construct();
		// read configuration
		$config = array();
		platcode()->config->import('memcache', $config);
		// connection type
		$connect = 'memcache_'.($config['is_persistant'] ? 'pconnect' : 'connect');
		// create resource
		$this->cacher = $connect($config['host'], $config['port']) or die('Memcache Connection Failed');
	}

	/**
	 * Set value in memory
	 * @param string $key
	 * @param mixed $value
	 * @param integer $ttl
	 * @param boolean $compress
	 */
	public function set($key, &$value, $ttl = 0, $compress = FALSE) {
		memcache_set($this->cacher, $key, $value, $compress ? MEMCACHE_COMPRESSED : FALSE, $ttl);
	}

	/**
	 * Fetch a memory value
	 * @param string $key
	 * @return string|boolean
	 */
	public function  __get($key) {
		return memcache_get($this->cacher, $key);
	}

	/**
	 * Get dropped value
	 * @param string $key
	 * @return string|boolean
	 */
	public function drop($key) {
		$value = memcache_get($this->cacher, $key);
		if ($value !== FALSE)
			memcache_delete($this->cacher, $key);
		return $value;
	}

	/**
	 * Read cached data
	 * @param string $key
	 * @return mixed|boolean
	 */
	public function read_cache($key) {
		$result = memcache_get($this->cacher, $key);
		return $result !== FALSE ? json_decode($result, TRUE) : FALSE;
	}

	/**
	 * Write a data in cache
	 * @param string $key
	 * @param mixed $data
	 */
	public function write_cache($key, &$data) {
		$this->set($key, json_encode($data));
	}

	/**
	 * Delete a key from cache
	 * @param string $key
	 */
	public function delete_cache($key) {
		memcache_delete($this->cacher, $key);
	}

	/**
	 * Get persistant plugin state
	 * @override
	 * @return boolean
	 */
	public function is_persistant() {
		return TRUE;
	}
}

// end of file